package com.zzsoft.first_app_demo.repository;

import com.zzsoft.first_app_demo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhanghb on 2018/7/17.
 * {@link User}{@link Repository}
 */
@Repository
public class UserRepository {

    /**
     * 采用内存型的存储方式  ->Map
     */
    private final ConcurrentMap<Integer,User> repository =new ConcurrentHashMap<Integer,User>();

    /**
     *
     */
    private static  final AtomicInteger idGenatate =new AtomicInteger();


    /**
     * 保存用户对象
     * @param user {@link User}
     * @return 如果保存成功，返回<code>true</code>，
     *                 否则，返回<code>false</code>
     */
    public boolean save(User user){
        //id从1开始
        Integer id = idGenatate.incrementAndGet();
        user.setId(id);
       return  repository.put(id,user)==null;
    }

    /**
     * 返回所有用户列表
     * @return
     */
    public Collection<User> findAll(){
       return repository.values();
    }
}
